﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;

namespace Tools.Utils
{
    public static class JsonHelper
    {
        public static JObject TryParse(this string str)
        {
            if (string.IsNullOrWhiteSpace(str)) return null;

            JObject json;
            try
            {
                json = JObject.Parse(str);
            }
            catch (System.Exception)
            {
                return null;
            }
            return json;
        }

        public static JArray TryParseArray(this string str)
        {
            if (string.IsNullOrWhiteSpace(str)) return null;

            JArray json;
            try
            {
                json = JArray.Parse(str);
            }
            catch (System.Exception)
            {
                return null;
            }
            return json;
        }

        public static JObject ToJson(this object obj)
        {
            if (obj == null) return null;

            JObject json;
            try
            {
                json = JObject.FromObject(obj);
            }
            catch (System.Exception)
            {
                return null;
            }
            return json;
        }
        public static string ToJsonStr(this object obj)
        {
            var json = obj.ToJson()?.ToString();
            if (string.IsNullOrWhiteSpace(json)) json = obj.SerializeObject() ?? "";
            return json;
        }
        public static T DeserializeObject<T>(this string source) where T : class
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(source);
            }
            catch (System.Exception)
            {
                return default(T);
            }
        }
        public static List<T> DeserializeObjects<T>(this string source)
        {
            try
            {
                return JsonConvert.DeserializeObject<List<T>>(source) ?? new List<T>();
            }
            catch (System.Exception)
            {
                return new List<T>();
            }
        }
        public static string SerializeObject(this object obj)
        {
            try
            {
                return JsonConvert.SerializeObject(obj);
            }
            catch (System.Exception)
            {
                return null;
            }
        }
    }
}
